package v1

import (
	"strconv"

	"gitee.com/cyanbleeze/go-image-management/internal/service"
	"gitee.com/cyanbleeze/go-image-management/pkg/app"
	"gitee.com/cyanbleeze/go-image-management/pkg/errcode"
	"github.com/gin-gonic/gin"
)

type Comment struct {
}

func NewComment() Comment {
	return Comment{}
}

func (c Comment) Create(ctx *gin.Context) {
	params := service.CreateCommentRequest{}
	res := app.NewResponse(ctx)
	valid, errs := app.BindAndValid(ctx, &params)
	if !valid {
		res.ToErrorResponse(errcode.InvalidParams.WithDetails(errs.Errors()...))
		return
	}
	svc := service.New(ctx)
	err := svc.CreateComment(&params)
	if err != nil {
		res.ToErrorResponse(errcode.ErrorCreateCommentFail.WithDetails(err.Error()))
		return
	}
	res.ToResponse(gin.H{})
}

func (c Comment) Update(ctx *gin.Context) {
	res := app.NewResponse(ctx)
	id, IDErr := strconv.Atoi(ctx.Param("id"))
	if IDErr != nil {
		res.ToErrorResponse(errcode.InvalidParams.WithDetails(IDErr.Error()))
		return
	}
	params := service.UpdateCommentRequest{ID: uint(id)}
	valid, errs := app.BindAndValid(ctx, &params)
	if !valid {
		res.ToErrorResponse(errcode.InvalidParams.WithDetails(errs.Errors()...))
		return
	}
	svc := service.New(ctx)
	err := svc.UpdateComment(&params)
	if err != nil {
		res.ToErrorResponse(errcode.ErrorUpdateCategoryFail.WithDetails(err.Error()))
		return
	}
	res.ToResponse(gin.H{})
}

func (c Comment) Delete(ctx *gin.Context) {
	params := service.DeleteCommentRequest{}
	res := app.NewResponse(ctx)
	id, err := strconv.Atoi(ctx.Param("id"))
	if err != nil {
		res.ToErrorResponse(errcode.InvalidParams.WithDetails(err.Error()))
		return
	}
	params.ID = uint(id)
	svc := service.New(ctx)
	err = svc.DeleteComment(&params)
	if err != nil {
		res.ToErrorResponse(errcode.ErrorDeleteCategoryFail.WithDetails(err.Error()))
		return
	}
	res.ToResponse(gin.H{})
}

func (c Comment) List(ctx *gin.Context) {
	params := service.CommentListRequest{}
	res := app.NewResponse(ctx)
	valid, errs := app.BindAndValid(ctx, &params)
	if !valid {
		res.ToErrorResponse(errcode.InvalidParams.WithDetails(errs.Errors()...))
		return
	}
	pager := app.Pager{
		Page:     app.GetPage(ctx),
		PageSize: app.GetPageSize(ctx),
	}
	svc := service.New(ctx)
	commentList, count, err := svc.GetCommentList(&params, &pager)
	if err != nil {
		res.ToErrorResponse(errcode.ErrorGetCommentListFail.WithDetails(err.Error()))
		return
	}

	res.ToResponseList(commentList, count)
}
